package server;

import java.io.IOException;
import java.net.*;

/**
 * The NetworkThread handles all incoming connections, and keep track on the
 * number of previous connections.
 * 
 * @author sw6c
 * 
 */
public class NetworkThread extends Thread {
	boolean done = false;
	ServerSocket serverSocket;
	int threadNumber = 0; // Used to keep track of connections

	/**
	 * Creates a new NetworkThread on the provided port.
	 * 
	 * @param port
	 *            The port number of which the NetworkThread should listen for
	 *            connections.
	 * @throws IOException
	 *             If there is a problem starting the ServerSocket.
	 */
	public NetworkThread(int port) throws IOException {
		serverSocket = new ServerSocket(port);
		System.out.println(String.format("Starting the server on port %1$d",
				port));
	}

	/**
	 * The main logic function for the NetworkThread. Will loop "forever"
	 * listening for new connections, increasing the threadNumber. Will reset the
	 * threadNumber if it reaches MAX_INT.
	 */
	public void run() {
		while (!done) {
			try {
				Socket socket = serverSocket.accept();

				ConnectionThread ct = new ConnectionThread(socket, threadNumber);
				ct.start();

				if (threadNumber != Integer.MAX_VALUE)
					threadNumber++;
				else
					threadNumber = 0;

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
